import os
from pydub import AudioSegment

def merge_music_with_metronome(music_dir="./music", metronome_path="clap_180bpm.mp3", output_path="final_mix.mp3"):
    # 读取所有 MP3 文件
    mp3_files = [f for f in os.listdir(music_dir) if f.lower().endswith(".mp3") and f != metronome_path]
    
    if not mp3_files:
        print("❌ 未找到任何 mp3 音乐文件。")
        return
    
    print(f"🎶 找到 {len(mp3_files)} 首歌曲：{mp3_files}")
    
    # 拼接所有歌曲
    combined_music = AudioSegment.empty()
    for file in mp3_files:
        song = AudioSegment.from_mp3(os.path.join(music_dir, file))
        combined_music += song

    # 读取节拍音
    metronome = AudioSegment.from_mp3(metronome_path)
    
    # 如果节拍音比音乐短，重复它
    if len(metronome) < len(combined_music):
        repeat_count = (len(combined_music) // len(metronome)) + 1
        metronome = metronome * repeat_count

    # 裁剪节拍音到音乐的长度
    metronome = metronome[:len(combined_music)]

    # 合成音频：叠加节拍音 + 音乐
    final = combined_music.overlay(metronome - 12)  # -6 分贝降低节拍音量，避免压过歌曲

    # 导出合成后的音频
    final.export(output_path, format="mp3")
    print(f"✅ 合成完成：{output_path}")

merge_music_with_metronome()
